package io.boot.common.aspect;

import io.boot.common.annotation.BaseData;
import io.boot.common.utils.BaseEntity;
import io.boot.common.utils.StringUtils;
import io.boot.modules.app.annotation.LoginUser;
import io.boot.modules.sys.controller.AbstractController;
import io.boot.modules.sys.entity.SysUserEntity;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;

/**
 * BaseEntity处理
 *
 * @author kyson
 */
@Aspect
@Component
public class BaseDataAspect extends AbstractController
{

    // 配置织入点
    @Pointcut("@annotation(io.boot.common.annotation.BaseData)")
    public void baseDataPointCut()
    {
    }

    @Before("baseDataPointCut()")
    public void doBefore(JoinPoint point) throws Throwable
    {
        handleBaseData(point);
    }

    protected void handleBaseData(final JoinPoint joinPoint)
    {
        // 获得注解
        BaseData baseData = getAnnotation(joinPoint);
        if (baseData == null)
        {
            return;
        }
        // 获取当前的用户
        SysUserEntity currentUser=getUser();
        if (currentUser != null)
        {
            // 如果是超级管理员，则不过滤数据
            if (currentUser.getUserId()!=null)
            {
                dataScopeFilter(joinPoint, currentUser, baseData.value());
            }
        }
    }

    /**
     * BaseEntity
     *
     * @param joinPoint 切点
     */
    public static void dataScopeFilter(JoinPoint joinPoint, SysUserEntity user, String value)
    {
        BaseEntity baseEntity = (BaseEntity) joinPoint.getArgs()[0];
        if("save".equals(value)){
            baseEntity.setCreateBy(user.getUserId());
            baseEntity.setCreateTime(new Date());
        }else if("update".equals(value)){
            baseEntity.setUpdateBy(user.getUserId());
            baseEntity.setUpdateTime(new Date());
        }
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private BaseData getAnnotation(JoinPoint joinPoint)
    {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null)
        {
            return method.getAnnotation(BaseData.class);
        }
        return null;
    }
}
